package com.chen.security.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.client.JdbcClientDetailsService;
import org.springframework.security.oauth2.provider.code.AuthorizationCodeServices;
import org.springframework.security.oauth2.provider.code.JdbcAuthorizationCodeServices;
import org.springframework.security.oauth2.provider.token.*;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;

import javax.annotation.Resource;
import javax.sql.DataSource;
import java.util.Arrays;

@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

    @Resource
    private BCryptPasswordEncoder passwordEncoder;

    @Resource
    private TokenStore tokenStore;

    @Resource
    private DataSource dataSource;

    @Autowired
    @Qualifier("myClientDetailsService")
    private ClientDetailsService clientDetailsService;

    @Resource
    private AuthorizationCodeServices authorizationCodeServices;

    @Resource
    private AuthenticationManager authenticationManager;

    @Resource
    private JwtAccessTokenConverter jwtAccessTokenConverter;

    // 配置客户端
    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {

        // 使用客户端详情服务
        clients.withClientDetails(clientDetailsService);

        // // 使用内存
        // clients.inMemory()
        //         // client_id，客户端id
        //         .withClient("client")
        //         // client-secret，客户端密钥
        //         .secret(passwordEncoder.encode("112233"))
        //         // 资源列表
        //         .resourceIds("test1")
        //         // 授权范围标识
        //         .scopes("all")
        //         // 支持的授权类型
        //         .authorizedGrantTypes("authorization_code", "password", "client_credential", "implicit", "refresh_token")
        //         // 是否自动授权，false是跳到授权页面
        //         .autoApprove(false)
        //         // 授权成功的回调地址
        //         .redirectUris("http://www.baidu.com");
    }

    // 配置令牌访问端点和令牌管理服务
    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) {
        endpoints
                // 认证管理器
                .authenticationManager(authenticationManager)
                // 授权码服务
                .authorizationCodeServices(authorizationCodeServices)
                // token管理服务
                .tokenServices(tokenService())
                // 访问令牌端点的请求类型
                .allowedTokenEndpointRequestMethods(HttpMethod.POST);
    }

    // 配置令牌端点的安全约束
    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) {
        security
                // 开放接口
                .tokenKeyAccess("permitAll()")
                .checkTokenAccess("permitAll()")
                // 允许表单认证
                .allowFormAuthenticationForClients();
    }

    // 令牌管理服务
    @Bean
    public AuthorizationServerTokenServices tokenService() {
        DefaultTokenServices service = new DefaultTokenServices();
        // 客户端详情服务
        // service.setClientDetailsService(clientDetailsService);
        // 支持刷新令牌
        service.setSupportRefreshToken(true);
        // 令牌存储策略
        service.setTokenStore(tokenStore);

        // 令牌增强，使用 jwt 令牌
        TokenEnhancerChain tokenEnhancerChain = new TokenEnhancerChain();
        tokenEnhancerChain.setTokenEnhancers(Arrays.asList(jwtAccessTokenConverter));
        service.setTokenEnhancer(tokenEnhancerChain);

        // 令牌默认有效期2小时
        service.setAccessTokenValiditySeconds(7200);
        // 刷新令牌默认有效期3天
        service.setRefreshTokenValiditySeconds(259200);
        return service;
    }

    // 客户端详情服务，需要从数据库查询允许接入的客户端
    @Bean("myClientDetailsService")
    public ClientDetailsService clientDetailsService(){
        ClientDetailsService clientDetailsService = new JdbcClientDetailsService(dataSource);
        // 配置客户端密钥加密方式
        ((JdbcClientDetailsService) clientDetailsService).setPasswordEncoder(passwordEncoder);
        return clientDetailsService;
    }

    // // 授权码服务，设置授权码保存策略
    // @Bean
    // public AuthorizationCodeServices authorizationCodeServices() {
    //     // 设置授权码模式的授权码如何存取，暂时采用内存方式
    //     return new InMemoryAuthorizationCodeServices();
    // }
    // 授权码服务，设置授权码保存策略
    @Bean
    AuthorizationCodeServices authorizationCodeServices(){
        return new JdbcAuthorizationCodeServices(dataSource);
    }
}
